package com.maixun.lib_comment.wedgit

import android.content.Context
import android.graphics.Canvas
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatImageView
import com.maixun.lib_comment.R

/**
 * 作者：Lmoumou
 * 时间：2020/9/9 17:17
 *
 * 旋转菊花
 */
class LoadingView : AppCompatImageView {
    constructor(context: Context) : this(context, null)
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        setImageResource(R.mipmap.loading_spinner)
        mFrameTime = 1000 / 12
        mUpdateViewRunnable = object : Runnable {
            override fun run() {
                mRotateDegrees += 30f
                mRotateDegrees = if (mRotateDegrees < 360) mRotateDegrees else mRotateDegrees - 360
                invalidate()
                if (mNeedToUpdateView) {
                    postDelayed(this, mFrameTime.toLong())
                }
            }
        }
    }

    private var mNeedToUpdateView = false
    private var mRotateDegrees = 0f
    private var mFrameTime: Int
    private var mUpdateViewRunnable: Runnable

    override fun onDraw(canvas: Canvas?) {
        canvas?.rotate(mRotateDegrees, width / 2.toFloat(), height / 2.toFloat())
        super.onDraw(canvas)
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        mNeedToUpdateView = true
        post(mUpdateViewRunnable)
    }

    override fun onDetachedFromWindow() {
        mNeedToUpdateView = false
        super.onDetachedFromWindow()
    }
}